﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Mvc;

namespace DFGK_WMS.WebAPI.Controllers.移库管理
{
    /// <summary>
    /// 移库单
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TransferBinOrderModelController : ControllerBase
    {

        public TransferBinOrderModelController(ITTransferBinOrderRepository tTransferBinOrderRepository, ITTransferBinOrderDetailRepository tTransferBinOrderDetailRepository, ITInventoryRepository tInventoryRepository, IUserRepository userRepository)
        {
            TTransferBinOrderRepository = tTransferBinOrderRepository;
            TTransferBinOrderDetailRepository = tTransferBinOrderDetailRepository;
            TInventoryRepository = tInventoryRepository;
            UserRepository = userRepository;
        }

        public ITTransferBinOrderRepository TTransferBinOrderRepository { get; }

        public ITTransferBinOrderDetailRepository TTransferBinOrderDetailRepository { get; }
        public ITInventoryRepository TInventoryRepository { get; }
        public IUserRepository UserRepository { get; }

        #region 移库单管理

        /// <summary>
        /// 提交数据 （增加/修改/删除 ）
        /// </summary>
        /// <param name="transferBinOrderModel"></param>
        /// <returns></returns>
        [HttpPost]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult SubmitTransferBinOrderData(TTransferBinOrderDTO transferBinOrder)
        {
            var IsOk = TTransferBinOrderRepository.SubmitTransferBinOrderData(transferBinOrder);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "保存失败！", "500"));
        }

        /// <summary>
        /// 查询全部移库单
        /// </summary>
        /// <param name="AsNoTracking"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinOrderList(string? AsNoTracking, int pageIndex = 1, int pageSize = 10)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var list = TTransferBinOrderRepository.GetTransferBinOrderList(AsNoTracking, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 根据Id获取移库单对象
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinOrderById(int tid)
        {
            if (tid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var tran = TTransferBinOrderRepository.GetTransferBinOrderById(tid);
            if (tran != null)
            {
                return Ok(BaseResult.Result(tran, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 移库单删除
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelTransferBinOrder(int tid)
        {
            if (tid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TTransferBinOrderRepository.DelTransferBinOrder(tid);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }

        /// <summary>
        /// 生成移库单编号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GenerateNum()
        {
            DateTime currentDateTime = DateTime.Now;
            string year = currentDateTime.ToString("yyyy");
            string month = currentDateTime.ToString("MM");
            string day = currentDateTime.ToString("dd");
            string hour = currentDateTime.ToString("HH");
            string minute = currentDateTime.ToString("mm");
            string second = currentDateTime.ToString("ss");
            string randomNumber = GenerateRandomNumber(1000000, 9999999).ToString();

            string dateTimeRandomNumber = $"{year}{month}{day}{hour}{minute}{second}{randomNumber}";

            return Ok(BaseResult.Result(dateTimeRandomNumber, "生成单号！", "200"));
        }    

        /// <summary>
        /// 获取物料库存库位
        /// </summary>
        /// <param name="MaterialId">物料Id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInventoryCellData(int MaterialId)
        {
            if(MaterialId<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var list = TInventoryRepository.GetInventoryList().Where(i => i.MaterialId == MaterialId).ToList();
            if (list.Count <= 0)
            {
                return Ok(BaseResult.Result(list, "查询失败!", "200", 0));
            }
            return Ok(BaseResult.Result(list.Select(t => new
            {
                QId = t.Id,
                QLocationId = t.LocationId,
                QLocationCode = t.LocationCode,
                QLocationName = t.LocationName,
                QWhId = t.WarehouseId,
                QWhName = t.WarehouseName,
                QWarehouseCode = t.WarehouseCode,             
                AvailableQTY = t.AvailableQty,

            }).ToList(), "查询成功！", "200", 0));
        }

        /// <summary>
        /// 获取移库的可用空仓位
        /// </summary>
        /// <param name="fromLocationId"></param>
        /// <param name="isPriorityFilling"></param>
        /// <param name="filterType"></param>
        /// <param name="toLogicalPartCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinedCellSelectData(string? toLogicalPartCode, int FromLocationId, bool isPriorityFilling = false, int filterType = 1)
        {
            var list = TTransferBinOrderRepository.GetEnabledCellListByFromLocationId(toLogicalPartCode, FromLocationId, isPriorityFilling, filterType);
            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询失败!", "500", 0));
            }
            return Ok(BaseResult.Result(list.Select(t => new
            {
                HId = t.Id,
                HName = t.Name,
                HCode = t.Code,
                HWhId = t.WhId,
                HWhName = t.WhName,
                HAreaId = t.AreaId,
                HAreaName = t.AreaName,


            }).ToList(), "查询成功！", "200", 0));
        }

        /// <summary>
        /// 查看移库单的详细信息
        /// </summary>
        /// <param name="Id">移库单id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SelectTransferBinOrder(int Id)
        {
            if (Id > 0)
            {
                var data = TTransferBinOrderRepository.SelectTransferBinOrder(Id);
                return Ok(BaseResult.Result(data, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "Id有误", "500"));
        }

        /// <summary>
        /// 执行移库单
        /// </summary>
        /// <param name="Id">移库单Id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult UpdateTransState(int Id)
        {
            if (Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool isOk = false;
            var tran = TTransferBinOrderRepository.GetTransferBinOrderById(Id);
            if (tran != null)
            {
                tran.Status = 3;
                isOk = TTransferBinOrderRepository.UpdateTransferBinOrder(tran);
            }
            if (isOk)
            {
                return Ok(BaseResult.Result(true, "执行成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "执行失败！", "500"));
        }

        /// <summary>
        /// 提交移库单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitTranState(SubmitTranDTO submitTranDTO)
        {
            var isok = TTransferBinOrderRepository.SubmitTranState(submitTranDTO);
            if (isok)
            {
                return Ok(BaseResult.Result(true, "提交成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "提交失败！", "500"));
        }

        #endregion

        #region 移库单明细管理

        /// <summary>
        /// 删除移库单明细
        /// </summary>
        /// <param name="Id">移库单明细id</param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelTransferBinOrderDetails(int Id)
        {
            if (Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TTransferBinOrderDetailRepository.DelTransferBinOrderDetails(Id);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));

        }
        #endregion

        private static int GenerateRandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
    }
}
